import { User, selectUserField } from '@/entity/User';
import { User as UserType } from '@/m_res/user'
import { Service, Inject } from 'typedi'
import { Entity } from '@/utils/orm'
import { addUser } from '@/model/request/User';
import moment from 'moment';
import md5 from 'md5';
import { JsonResult, msgList, res } from '@/utils/jsonResult';
import jsonwebtoken from 'jsonwebtoken'
import config from '@/config'

@Service()
export class UserDao {

    @Inject()
    entity!: Entity

    @Inject()
    json!: JsonResult<any>;

    async GetOneUser(id: number): Promise<res<UserType | null>> {
        let data = <UserType>await this.entity.get(User).findOne({
            select: selectUserField,
            where: { user_id: id }
        });
        if (data) {
            return this.json.success(data)
        } else {
            return this.json.success(null,msgList.NoFound)
        }
    }

    async addUserDao(params: addUser): Promise<res<null>> {
        let isHave = await this.entity.get(User).findOne({
            where: { "user_name": params.name }
        });
        console.log("isHave: ", isHave);
        
        if (isHave != null) {
            return this.json.success(null, msgList.UserNameExist)
        } else {
            await this.entity.source()
            .insert()
            .into(User)
            .values([
                { 
                    user_name: params.name, 
                    user_img: "https://upload.jianshu.io/users/upload_avatars/3136195/484e32c3504a.jpg?imageMogr2/auto-orient/strip|imageView2/1/w/240/h/240",
                    user_pwd: md5(params.pwd),
                    user_type: 0,
                    user_addtime: moment().valueOf()
                },
            ])
            .execute()

            return this.json.success(null, msgList.addUserSuccess)
        }
    }

    async LoginDao(params: addUser): Promise<res<UserType | null>> {
        // const user = await this.entity.get(User).findOneBy({
        //     user_name: params.name,
        //     user_pwd: md5(params.pwd),
        // })
        const user = await this.entity.repository(User)
        .where("user.user_name = :user_name", { user_name: params.name }) 
        .andWhere('user.user_pwd = :user_pwd', { user_pwd: md5(params.pwd) })
        .getOne()
        
        if (user) {
            var token = jsonwebtoken.sign({
                user_id: user.user_id,
                user_name: user.user_name
            }, config.jwtKey);
            return this.json.success(token)
        } else {
            return this.json.error(null,msgList.PasswordError)
        }
    }
}